from django.db.models import Q, Avg, F
from django.http import HttpResponse
from django.shortcuts import render
from .models import EmpChoices, SexChoices, Employee, DeptModel


# Create your views here.

def test01(request):
    # Employee.objects.create(name="zs", emp=EmpChoices.PM, last=3000, j_last=340.2, sex=SexChoices.O, b_lz=False)
    # Employee.objects.create(name="ls", emp=EmpChoices.PM, last=6000, j_last=670.2, sex=SexChoices.L, b_lz=False)
    # Employee.objects.create(name="ww", emp=EmpChoices.PM, last=8000, j_last=890.2, sex=SexChoices.O, b_lz=False)
    # Employee.objects.create(name="sl", emp=EmpChoices.PM, last=2000, j_last=230.2, sex=SexChoices.L, b_lz=False)
    # Employee.objects.create(name="ll", emp=EmpChoices.PM, last=9000, j_last=930.2, sex=SexChoices.O, b_lz=False)

    # 查询工资大于7000的
    x = Employee.objects.filter(last__gt=7000)
    print(x)
    print('-----------')
    # 使用模糊查询
    w = Employee.objects.filter(name__contains='l')
    print(w)
    # Q查询
    # 我们要查询员工名字中包含l 或者（薪资大于7000 并且 是女的 ）
    print('--------------')
    xx = Employee.objects.filter(Q(Q(name__contains='l') | Q(Q(last__gt=2000)) & Q(sex='女')))
    for i in xx:
        print(i)
    print("-----all----")
    rel = Employee.objects.all()
    for i in rel:
        print(i)
    print('------max--------')
    xs = Employee.objects.filter(Q(Q(name='zs') | Q(Q(last=3000) & Q(sex='女'))))
    for i in xs:
        print(i)
    print('------------agg-------')
    # 统计工资大于5000的
    la = Employee.objects.aggregate(avg_la=Avg('last'))
    print(la)
    print('------------')
    # Employee.objects.filter(name='zs').update(last=F('last')+120)
    # 查询张三 修改张三的工资加1000 精铁加 320
    # Employee.objects.filter(name='zs').update(last=F('last')+1000,j_last=F('j_last')+320)
    # 删除工资小于2100的用户
    Employee.objects.filter(last__lt=2100).delete()
    return HttpResponse("model_two_test1")


# 这个主要是弄的关联关系
def test02(request):
    # 创建属性
    # d1 = DeptModel.objects.create(name="四川")
    #
    # d2 = DeptModel.objects.create(name="成都", prent=d1)
    # d3 = DeptModel.objects.create(name="绵阳", prent=d1)
    #
    # d4 = DeptModel.objects.create(name="清阳区", prent=d2)
    # 删除某个部门并且后面的关联属性删除
    # x = DeptModel.objects.filter(pk=5).delete()
    # 删除了这个部门我们需要重新添加一个部门把这个值关联回去
    # x = DeptModel.objects.create(name="成都1", prent_id=4)
    # DeptModel.objects.filter(name='清阳区').update(prent_id=x.id)
    d = DeptModel.objects.filter(prent__name='四川')
    for i in d:
        print(i)
    return HttpResponse("model_two_test2")
